import { memo, useState, useCallback } from 'react';
import { useProjectStore, useFileTree, useFileOperations } from '../../stores';
import FileContextMenu from './FileContextMenu';
import { Dialog, DialogFooter, Button, Input } from '../common';
import globalEventManager, { FILE_EVENTS } from '../../utils/eventManager';
import { FaPython, FaFileCode, FaRegFileLines, FaBook, FaRegFolder, FaFolderOpen, FaEllipsisVertical, FaChevronRight, FaChevronDown, FaFile } from 'react-icons/fa6';
import { globalPlayer } from 'python-player';
import styles from './FileTree.module.css';

const FileTreeItem = memo(({ file, isActive, onFileClick, onFileAction, level = 0, isExpanded, onToggleExpand }) => {
  const handleClick = () => {
    if (file.type === 'directory') {
      onToggleExpand(file.id);
    } else {
      onFileClick(file.id);
    }
  };


  const handleActionClick = (event) => {
    event.preventDefault();
    event.stopPropagation();
    onFileAction(event, file);
  };

  const getFileIcon = (file) => {
    // 使用type属性判断是否为文件夹
    if (file.type === 'directory') {
      // 根据展开状态显示不同的文件夹图标
      // console.log(`文件夹图标: ${file.name}, 展开状态: ${isExpanded}`);
      return isExpanded ? 
        <FaFolderOpen className={styles.folderIcon} /> : 
        <FaRegFolder className={styles.folderIcon} />;
    }
    
    const fileName = file.name || '';
    const extension = fileName.split('.').pop()?.toLowerCase();
    switch (extension) {
      case 'py':
        return <FaPython className={styles.fileIcon} />;
      case 'js':
        return <FaFileCode className={styles.fileIcon} />;
      case 'json':
        return <FaFile className={styles.fileIcon} />;
      case 'txt':
        return <FaRegFileLines className={styles.fileIcon} />;
      case 'md':
        return <FaBook className={styles.fileIcon} />;
      default:
        return <FaFileCode className={styles.fileIcon} />;
    }
  };

  const getExpandIcon = () => {
    if (file.type !== 'directory') return null;
    return isExpanded ? 
      <FaChevronDown className={styles.expandIcon} /> : 
      <FaChevronRight className={styles.expandIcon} />;
  };

  const isDir = file.type === 'directory';
  // console.log(`渲染文件项: ${file.name}`, {
  //   isDir,
  //   level,
  //   type: file.type,
  //   name: file.name
  // });
  
  return (
    <div
      className={`${styles.fileItem} ${isActive ? styles.active : ''} ${isDir ? styles.folderItem : ''}`}
      onClick={handleClick}
      style={{ paddingLeft: `${16 + level * 20}px` }}
    >
      <div className={styles.expandButton}>
        {getExpandIcon()}
      </div>
      {getFileIcon(file)}
      <span className={styles.fileName}>
        {file.name || '未命名'}
      </span>
      {file.isDirty && (
        <span className={styles.dirtyIndicator} title="文件已修改">
          ●
        </span>
      )}
      <div className={styles.fileActions}>
        <button
          className={styles.actionButton}
          onClick={handleActionClick}
          title="文件操作"
        >
          <FaEllipsisVertical />
        </button>
      </div>
    </div>
  );
});

FileTreeItem.displayName = 'FileTreeItem';

const FileTree = memo(() => {
  const { 
    getAllFiles, 
    getCurrentOpenedFileId,
    openFile,
    setCurrentFile,
    isFileOpened
  } = useProjectStore();

  const {
    selectedFileId,
    setSelectedFile,
    expandedFolders,
    toggleFolder
  } = useFileTree();

  const { fileOperations } = useFileOperations();

  // 构建树状结构
  const buildFileTree = useCallback((files, parentId = 0, level = 0) => {
    const children = files.filter(file => file && file.parentId === parentId);
    const result = [];
    
    // 排序：文件夹优先，然后按字母顺序排序
    const sortedChildren = children.sort((a, b) => {
      const aIsDir = a.type === 'directory';
      const bIsDir = b.type === 'directory';
      
      // 文件夹优先
      if (aIsDir && !bIsDir) return -1;
      if (!aIsDir && bIsDir) return 1;
      
      // 同类型按字母顺序排序
      return (a.name || '').localeCompare(b.name || '');
    });
    
    sortedChildren.forEach(file => {
      // 确保文件对象有必要的属性
      if (!file.id) {
        console.warn('文件对象缺少id属性:', file);
        return;
      }
      
      const fileWithLevel = { ...file, level };
      result.push(fileWithLevel);
      
      // 如果是文件夹且已展开，递归添加子项
      if (file.type === 'directory' && expandedFolders.has(file.id)) {
        result.push(...buildFileTree(files, file.id, level + 1));
      }
    });
    
    return result;
  }, [expandedFolders]);

  // 上下文菜单状态
  const [contextMenu, setContextMenu] = useState({
    isVisible: false,
    position: { x: 0, y: 0 },
    targetFile: null
  });

  // 新建文件的父目录上下文
  const [newFileParentContext, setNewFileParentContext] = useState(null);

  // 新建文件对话框状态
  const [newFileDialog, setNewFileDialog] = useState({
    isOpen: false,
    fileName: ''
  });

  // 新建文件夹对话框状态
  const [newFolderDialog, setNewFolderDialog] = useState({
    isOpen: false,
    folderName: ''
  });

  // 删除确认对话框状态
  const [deleteConfirm, setDeleteConfirm] = useState({
    isOpen: false,
    file: null
  });

  // 重命名对话框状态
  const [renameDialog, setRenameDialog] = useState({
    isOpen: false,
    file: null,
    newName: ''
  });

  const files = getAllFiles();
  const currentFileId = getCurrentOpenedFileId();

  const handleFileClick = async (fileId) => {
    // 设置为 sidebar 选中的文件
    setSelectedFile(fileId);
    
    // 触发文件选中事件
    globalEventManager.emit(FILE_EVENTS.SELECTED, { fileId });
    
    // 如果文件未打开，先打开它
    if (!isFileOpened(fileId)) {
      openFile(fileId);
      // 触发文件打开事件
      globalEventManager.emit(FILE_EVENTS.OPENED, { fileId });
    }
    // 设置为当前文件
    await setCurrentFile(fileId);
  };

  // 右键菜单处理
  const handleContextMenu = useCallback((event, file) => {
    event.preventDefault();
    event.stopPropagation();
    
    console.log('=== 右键菜单触发 ===');
    console.log('右键点击的文件:', file);
    console.log('文件类型:', file?.type);
    console.log('文件ID:', file?.id);
    console.log('文件父ID:', file?.parentId);
    console.log('当前selectedFileId:', selectedFileId);
    console.log('==================');
    
    // 设置新建文件的父目录上下文
    setNewFileParentContext(file);
    
    setContextMenu({
      isVisible: true,
      position: { x: event.clientX, y: event.clientY },
      targetFile: file
    });
  }, [selectedFileId]);

  // 文件操作按钮处理
  const handleFileAction = useCallback((event, file) => {
    event.preventDefault();
    event.stopPropagation();
    
    console.log('=== 文件操作按钮触发 ===');
    console.log('操作按钮点击的文件:', file);
    console.log('文件类型:', file?.type);
    console.log('文件ID:', file?.id);
    console.log('文件父ID:', file?.parentId);
    console.log('当前selectedFileId:', selectedFileId);
    console.log('========================');
    
    // 设置新建文件的父目录上下文
    setNewFileParentContext(file);
    
    setContextMenu({
      isVisible: true,
      position: { x: event.clientX, y: event.clientY },
      targetFile: file
    });
  }, [selectedFileId]);

  const handleCloseContextMenu = useCallback(() => {
    setContextMenu({ isVisible: false, position: { x: 0, y: 0 }, targetFile: null });
  }, []);

  // 文件操作处理
  const handleNewFile = useCallback(() => {
    setNewFileDialog({ isOpen: true, fileName: '' });
  }, []);

  const handleNewFolder = useCallback(() => {
    setNewFolderDialog({ isOpen: true, folderName: '' });
  }, []);

  const handleDeleteFile = useCallback((file) => {
    setDeleteConfirm({ isOpen: true, file });
  }, []);

  const handleRenameFile = useCallback((file) => {
    setRenameDialog({
      isOpen: true,
      file: file,
      newName: file.name
    });
  }, []);

  // 确认新建文件
  const handleConfirmNewFile = useCallback(async () => {
    if (newFileDialog.fileName.trim()) {
      const fileName = newFileDialog.fileName.trim();
      // 获取新建文件的父目录ID
      let parentId = 0; // 默认根目录
      
      console.log('=== 新建文件调试信息 ===');
      console.log('newFileParentContext:', newFileParentContext);
      console.log('fileName:', fileName);
      
      if (newFileParentContext) {
        console.log('parentContext.type:', newFileParentContext.type);
        console.log('parentContext.id:', newFileParentContext.id);
        console.log('parentContext.parentId:', newFileParentContext.parentId);
        
        // 如果父目录上下文是文件夹，在该文件夹下创建
        if (newFileParentContext.type === 'directory') {
          parentId = newFileParentContext.id;
          console.log('选择在文件夹下创建，parentId:', parentId);
        }
        // 如果父目录上下文是文件，在文件的父目录下创建
        else if (newFileParentContext.type === 'file') {
          parentId = newFileParentContext.parentId || 0;
          console.log('选择在文件父目录下创建，parentId:', parentId);
        }
      } else {
        console.log('没有父目录上下文，使用根目录');
      }
      
      console.log('最终使用的parentId:', parentId);
      console.log('========================');
      
      const result = await fileOperations.createFile(fileName, '', parentId);
      
      if (result.success) {
        console.log('文件创建成功:', fileName);
        // 可以显示成功消息
      } else {
        console.error('文件创建失败:', result.error);
        // 可以显示错误消息
      }
    }
    setNewFileDialog({ isOpen: false, fileName: '' });
  }, [newFileDialog.fileName, fileOperations, newFileParentContext]);

  // 确认新建文件夹
  const handleConfirmNewFolder = useCallback(async () => {
    if (newFolderDialog.folderName.trim()) {
      const folderName = newFolderDialog.folderName.trim();
      // 获取新建文件夹的父目录ID
      let parentId = 0; // 默认根目录
      
      console.log('=== 新建文件夹调试信息 ===');
      console.log('newFileParentContext:', newFileParentContext);
      console.log('folderName:', folderName);
      
      if (newFileParentContext) {
        console.log('parentContext.type:', newFileParentContext.type);
        console.log('parentContext.id:', newFileParentContext.id);
        console.log('parentContext.parentId:', newFileParentContext.parentId);
        
        // 如果父目录上下文是文件夹，在该文件夹下创建
        if (newFileParentContext.type === 'directory') {
          parentId = newFileParentContext.id;
          console.log('选择在文件夹下创建，parentId:', parentId);
        }
        // 如果父目录上下文是文件，在文件的父目录下创建
        else if (newFileParentContext.type === 'file') {
          parentId = newFileParentContext.parentId || 0;
          console.log('选择在文件父目录下创建，parentId:', parentId);
        }
      } else {
        console.log('没有父目录上下文，使用根目录');
      }
      
      console.log('最终使用的parentId:', parentId);
      console.log('==========================');
      
      const result = await fileOperations.createFolder(folderName, parentId);
      
      if (result.success) {
        console.log('文件夹创建成功:', folderName);
        // 可以显示成功消息
      } else {
        console.error('文件夹创建失败:', result.error);
        // 可以显示错误消息
      }
    }
    setNewFolderDialog({ isOpen: false, folderName: '' });
  }, [newFolderDialog.folderName, fileOperations, newFileParentContext]);

  // 确认重命名文件
  const handleConfirmRename = useCallback(async () => {
    if (renameDialog.newName.trim() && renameDialog.file) {
      const result = await fileOperations.renameFile(renameDialog.file.id, renameDialog.newName.trim());
      
      if (result.success) {
        console.log('文件重命名成功:', renameDialog.newName);
        // 可以显示成功消息
      } else {
        console.error('文件重命名失败:', result.error);
        // 可以显示错误消息
      }
    }
    setRenameDialog({ isOpen: false, file: null, newName: '' });
  }, [renameDialog.newName, renameDialog.file, fileOperations]);

  // 确认删除文件
  const handleConfirmDelete = useCallback(async () => {
    if (deleteConfirm.file) {
      const result = await fileOperations.deleteFile(deleteConfirm.file.id);
      
      if (result.success) {
        console.log('文件删除成功:', deleteConfirm.file.name);
        // 可以显示成功消息
      } else {
        console.error('文件删除失败:', result.error);
        // 可以显示错误消息
      }
    }
    setDeleteConfirm({ isOpen: false, file: null });
  }, [deleteConfirm.file, fileOperations]);

  if (!files || files.length === 0) {
    return (
      <div className={styles.emptyState}>
        <FaRegFolder className={styles.emptyIcon} />
        <div className={styles.emptyText}>暂无文件</div>
        <div className={styles.emptyHint}>创建一个新文件开始编程</div>
      </div>
    );
  }

  // 构建树状结构
  const treeFiles = buildFileTree(files);

  return (
    <>
      <div className={styles.fileTree}>
        <div 
          className={styles.fileList}
          onContextMenu={(e) => handleContextMenu(e, null)} // 空白区域右键菜单
        >
          {treeFiles.map((file, index) => (
            <div
              key={`${file.id || 'unknown'}-${file.level || 0}-${index}`}
              onContextMenu={(e) => handleContextMenu(e, file)}
            >
              <FileTreeItem
                file={file}
                isActive={file.id === currentFileId || file.id === selectedFileId}
                onFileClick={handleFileClick}
                onFileAction={handleFileAction}
                level={file.level}
                isExpanded={expandedFolders.has(file.id)}
                onToggleExpand={toggleFolder}
              />
            </div>
          ))}
        </div>
      </div>

      {/* 右键菜单 */}
      <FileContextMenu
        isVisible={contextMenu.isVisible}
        position={contextMenu.position}
        selectedFile={contextMenu.targetFile}
        onClose={handleCloseContextMenu}
        onNewFile={handleNewFile}
        onNewFolder={handleNewFolder}
        onDeleteFile={handleDeleteFile}
        onRenameFile={handleRenameFile}
        onOpenFile={handleFileClick}
      />

      {/* 新建文件对话框 */}
      <Dialog
        isOpen={newFileDialog.isOpen}
        onClose={() => setNewFileDialog({ isOpen: false, fileName: '' })}
        title="新建文件"
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setNewFileDialog({ isOpen: false, fileName: '' })}
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={handleConfirmNewFile}
              disabled={!newFileDialog.fileName.trim()}
            >
              创建
            </Button>
          </>
        }
      >
        <Input
          value={newFileDialog.fileName}
          onChange={(e) => setNewFileDialog({ ...newFileDialog, fileName: e.target.value })}
          placeholder="输入文件名 (例如: main.py)"
          label="文件名"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleConfirmNewFile();
            }
          }}
        />
      </Dialog>

      {/* 新建文件夹对话框 */}
      <Dialog
        isOpen={newFolderDialog.isOpen}
        onClose={() => setNewFolderDialog({ isOpen: false, folderName: '' })}
        title="新建文件夹"
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setNewFolderDialog({ isOpen: false, folderName: '' })}
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={handleConfirmNewFolder}
              disabled={!newFolderDialog.folderName.trim()}
            >
              创建
            </Button>
          </>
        }
      >
        <Input
          value={newFolderDialog.folderName}
          onChange={(e) => setNewFolderDialog({ ...newFolderDialog, folderName: e.target.value })}
          placeholder="输入文件夹名称"
          label="文件夹名称"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleConfirmNewFolder();
            }
          }}
        />
      </Dialog>

      {/* 重命名文件对话框 */}
      <Dialog
        isOpen={renameDialog.isOpen}
        onClose={() => setRenameDialog({ isOpen: false, file: null, newName: '' })}
        title={`重命名${renameDialog.file?.type === 'directory' ? '文件夹' : '文件'}`}
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setRenameDialog({ isOpen: false, file: null, newName: '' })}
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={handleConfirmRename}
              disabled={!renameDialog.newName.trim()}
            >
              确认
            </Button>
          </>
        }
      >
        <Input
          value={renameDialog.newName}
          onChange={(e) => setRenameDialog(prev => ({ ...prev, newName: e.target.value }))}
          placeholder="请输入新名称"
          label="新名称"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleConfirmRename();
            }
          }}
        />
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, file: null })}
        title="确认删除"
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setDeleteConfirm({ isOpen: false, file: null })}
            >
              取消
            </Button>
            <Button
              variant="danger"
              onClick={handleConfirmDelete}
            >
              删除
            </Button>
          </>
        }
      >
        {deleteConfirm.file?.type === 'directory' ? (
          <>
            <p>确定要删除文件夹 <strong>{deleteConfirm.file?.name}</strong> 吗？</p>
            <p className={styles.warningText}>
              <strong>警告：</strong>这将删除文件夹及其所有内容，包括所有子文件和子文件夹。
            </p>
            <p className={styles.warningText}>此操作无法撤销。</p>
          </>
        ) : (
          <>
            <p>确定要删除文件 <strong>{deleteConfirm.file?.name}</strong> 吗？</p>
            <p className={styles.warningText}>此操作无法撤销。</p>
          </>
        )}
      </Dialog>
    </>
  );
});

FileTree.displayName = 'FileTree';

export default FileTree;
